from __future__ import absolute_import
from lxml import etree
import fnmatch
import logging
logger = logging.getLogger('pkgr.groups')
from pkgr.group import Group

class Groups(object):
    def __init__(self):
        self.list = []
        self.idmap = {}
        
    def get_groups(self):
        return self.list
        
    def search_by_id(self, id):
        return self.idmap.get(id, None)
        
    def search_by_name_glob(self, name):
        matches = []
        name = name.lower()
        for group in self.get_groups():
            if fnmatch.fnmatch(group.get_name().lower(), name):
                matches.append(group)
        return matches
        
    def add_group(self, group):
        self.idmap[group.get_id()] = group
        self.list.append(group)
        
    def load(self, f):
        self._load(f.read())
        
    def load_file(self, path):
        self._load(open(path).read())
        
    def _load(self, d):
        root = etree.XML(d)
        self.idmap = {}
        for group in root:
            # simple copy from xml
            id = group.find('id')
            # XXX: apparently there are some without ids
            if id is None:
                continue
            
            id = id.text
            name = group.find('name').text
            description = group.find('description').text
            default = group.find('default')
            
            if default is None or default.text == "false":
                default = False
            else:
                default = True
                
            uservisible = group.find('uservisible')
            if uservisible is None or uservisible.text == "false":
                uservisible = False
            else:
                uservisible = True
             
            langonly = group.find('langonly')
            if langonly is not None:
                langonly = langonly.text
            # build the package map
            newgroup = Group(id, name, description, default, uservisible)
            newgroup.langonly = langonly
            
            for package in group.findall('.//packagereq'):
                newgroup.add_package(package.text, package.get('type'))
                
            self.add_group(newgroup)
            
